package com.lv.suyiyong.hfrbusines.ui

import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.View.OnClickListener
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.chad.library.adapter.base.listener.OnItemDragListener
import com.lihang.ShadowLayout
import com.lv.common.base.BaseActivity
import com.lv.common.dialog.HintDialog
import com.lv.common.imp.ItemTouchHelperViewHolder
import com.lv.common.imp.OnDialogSureListener
import com.lv.common.imp.OnPositionTListener
import com.lv.common.ktx.setMaxLength
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.AnimationUtils
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.showToast
import com.lv.suyiyong.hfrbusines.R
import com.lv.suyiyong.hfrbusines.adapter.BnamesAdapter
import com.lv.suyiyong.hfrbusines.databinding.ActivityBnamesBinding


/**
 * 作者： ygx
 * 创建日期：2023/6/6 3:52 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：主营
 */
@Route(path = ARoutUtils.ManagerBnamesActivity)
class ManagerBnamesActivity : BaseActivity<ActivityBnamesBinding>(),
    OnClickListener {
    @Autowired(name = "bnames")
    @JvmField
    var mIntentData: ArrayList<String>? = null

    @Autowired(name = "type")
    @JvmField
    var mType: Int = 0//0 主营 1 经营范围


    private var mPosition: Int = 0
    private val mBeans = arrayListOf<String>()
    private var mAdapter: BnamesAdapter? = null
    private var managerDialog: HintDialog? = null
    override fun getLayoutRes() = R.layout.activity_bnames
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            StatusBarUtil.setHeightAndPadding(this@ManagerBnamesActivity, titleBar)
            titleBar.onClickBackIcon { finish() }
            tvAdd.setOnClickListener(this@ManagerBnamesActivity)
            tvSubmit.setOnClickListener(this@ManagerBnamesActivity)
        }

    }


    override fun initData() {
        super.initData()

    }

    override fun initConfig() {
        super.initConfig()
        if (!mIntentData.isNullOrEmpty()) {
            mBeans.clear()
            mBeans.addAll(mIntentData!!)
        }
        when (mType) {
            0 -> mBinding.titleBar.setTitle("主营")
            1 -> {
                mBinding.titleBar.setTitle("经营范围")
                mBinding.etContent.hint = "请输入经营范围"
                mBinding.tvCaption.text = "备注：经营范围为1-5个字符"
                mBinding.tvBottomHint.visibility = View.GONE
                mBinding.etContent.setMaxLength(5)
            }
        }
//        when (mThemeType) {
//            "0" -> {
//                mBinding.tvAdd.setBackgroundResource(com.lv.common.R.drawable.bg_theme_r_5)
//                mBinding.tvSubmit.setBackgroundResource(com.lv.common.R.drawable.bg_theme_5)
//            }
//
//            "1" -> {
//                mBinding.tvAdd.setBackgroundResource(com.lv.common.R.drawable.bg_theme_r_5)
//                mBinding.tvSubmit.setBackgroundResource(com.lv.common.R.drawable.bg_theme_20)
//                mBinding.tvSubmit.layoutParams.height = SizeUtils.dp2px(38.0f)
//            }
//        }
        initRecyclerView()


    }

    private fun initRecyclerView() {

        mAdapter = BnamesAdapter(mBeans)
        mBinding.rvContent.adapter = mAdapter
        mAdapter?.draggableModule?.isDragEnabled = true
        mAdapter?.draggableModule?.setOnItemDragListener(object : OnItemDragListener {
            //拖拽开始
            override fun onItemDragStart(viewHolder: RecyclerView.ViewHolder?, pos: Int) {
                val shadowLayout =
                    viewHolder?.itemView?.findViewById<ShadowLayout>(R.id.shadow_layout)
                val clParent = viewHolder?.itemView?.findViewById<ConstraintLayout>(R.id.cl_parent)
                if (viewHolder is ItemTouchHelperViewHolder) {
                    val itemViewHolder = viewHolder as ItemTouchHelperViewHolder
                    itemViewHolder.onItemSelected(shadowLayout)
                    clParent?.scaleY = 0.94f
                }
            }

            /**
             * 因拖拽而发生位置互换时回调
             * @param source    非用户拖拽的那个改变位置的Item
             * @param from    用户拖拽的Item换位之前的position
             * @param target    用户拖拽的Item
             * @param to    用户拖拽的Item换位之后的position
             */
            override fun onItemDragMoving(
                source: RecyclerView.ViewHolder?,
                from: Int,
                target: RecyclerView.ViewHolder?,
                to: Int
            ) {
            }

            //拖拽结束
            override fun onItemDragEnd(viewHolder: RecyclerView.ViewHolder?, pos: Int) {
                val shadowLayout =
                    viewHolder?.itemView?.findViewById<ShadowLayout>(R.id.shadow_layout)
                val clParent = viewHolder?.itemView?.findViewById<ConstraintLayout>(R.id.cl_parent)

                if (viewHolder is ItemTouchHelperViewHolder) {
                    val itemViewHolder = viewHolder as ItemTouchHelperViewHolder
                    itemViewHolder.onItemClear(shadowLayout)
                    clParent?.scaleY = 1.0f

                }
            }
        })
    }


    /**
     * @param type 0 添加 1 删除
     * @param name
     */
    private fun editorIntroduce(type: String, name: String) {
        if (type == "0") {//添加成功
            mBinding.etContent.setText("")
            mBeans.add(name)
            mAdapter?.notifyDataSetChanged()
            mBinding.rvContent.smoothScrollToPosition(mBeans.size)
        } else {
            mBeans.removeAt(mPosition)
            mAdapter?.notifyItemRemoved(mPosition)
            mAdapter?.notifyItemRangeChanged(mPosition, mBeans.size)
        }
    }


    override fun initEvents() {
        super.initEvents()
        //删除
        mAdapter?.onViewCutClickListener = OnPositionTListener { position, data ->
            mPosition = position
            showManagerDialog("1", data ?: "")

        }

    }


    /**
     * @param type 0 添加已满 1 可以删除提示
     */
    private fun showManagerDialog(type: String, name: String = "") {
        var hint = ""
        if (type == "0") {//添加
            hint = "主营商品已满（20个），您可以删除其他内容后，再进行添加。"
        } else if (type == "1") {
            hint = "确认要删除该主营商品吗？"
        }
        managerDialog = HintDialog(this, "提示", hint, true, true, OnDialogSureListener {
            if (type == "1") {//删除
                editorIntroduce(type, name)
            }
        }, type == "1")
        managerDialog?.show()
        managerDialog?.setSurColor(Color.parseColor("#026DFF"))
    }


    override fun onResume() {
        super.onResume()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_add -> {
                if (mBeans.size >= 20) {
                    showManagerDialog("0")
                    return
                }
                val tag = mBinding.etContent.text.toString().trim()
                if (tag.isEmpty()) {
                    showToast("请输入主营商品")
                    AnimationUtils.setHintAnimation(mBinding.etContent)
                    return
                }
                if (tag.isNotEmpty()) {
                    val tags = mBeans.find { it == tag }
                    if (tags != null) {
                        showToast("主营商品不能重复")
                        return
                    }
                }
                editorIntroduce("0", tag)

            }

            R.id.tv_submit -> {//保存
                if (mBeans.isEmpty()) {
                    showToast("请输入主营商品")
                } else {
                    val bundle = Bundle()
                    bundle.putSerializable("introduce", mBeans)
                    intent.putExtras(bundle)
                    setResult(RESULT_OK, intent)
                    finish()
                }

            }

        }
    }


    override fun onDestroy() {
        super.onDestroy()
        if (managerDialog?.isShowing == true) {
            managerDialog?.dismiss()
        }

    }
}